from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from community.models import Article, Comment


class ArticleSerializer(ModelSerializer):
    label_name = serializers.CharField(source='label.name', read_only=True)
    user_name = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = Article
        # fields = '__all__'
        exclude = ['is_delete']
        extra_kwargs = {
            'label': {'write_only': True},
            'user': {'write_only': True},
        }


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avater = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    # 这个方法可以调用这个序列化器上的某个方法返回的值。比如这里可以获取get_reply_name返回的值
    reply_name = SerializerMethodField()

    class Meta:
        model = Comment
        fields = '__all__'

    def get_reply_name(self, comment):
        try:
            # 拿到自动生成的评论模型的主键id为被回复的id的评论的用户
            user = Comment.objects.get(id=comment.reply_comment).user
            reply_name = user.first_name
        except:
            reply_name = None
        return reply_name


class CommentHandlerSerializer(ModelSerializer):
    # 这个方法可以调用这个序列化器上的某个方法返回的值。比如这里可以获取get_son_comment返回的值
    son_comment = SerializerMethodField()
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avater = serializers.CharField(source='user.userdetail.avatar', read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'

    def get_son_comment(self, comment):
        # 查询所有parent_comment(评论的id)为comment.id(自动生成的评论模型的主键id)的评论
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()  # 数据排序反转，变正序
        return data
